package in.muton.wicket.extensions.upload;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadWebRequest;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.util.upload.FileItemFactory;
import org.apache.wicket.util.upload.FileUploadException;

public class MultipartRequest extends MultipartServletWebRequest {
	
	private static Log log = LogFactory.getLog(MultipartRequest.class);

	public MultipartRequest(HttpServletRequest request, Bytes maxSize)
	throws FileUploadException 
	{
		super(request, maxSize);
		if(request == null)
			throw new IllegalArgumentException("Request cant be null");
	}

	public MultipartRequest(HttpServletRequest request, Bytes maxSize,
			FileItemFactory factory) throws FileUploadException {
		
		super(request, maxSize, factory);
		if(request == null)
			throw new IllegalArgumentException("Request cant be null");
		
	}

	@Override
	protected boolean wantUploadProgressUpdates() {
		return true;
	}
	
	@Override
	protected void onUploadStarted(int totalBytes) {
		log.debug("Starting Upload.");
		UploadProcessInfo info = new UploadProcessInfo(totalBytes);
		HttpServletRequest request = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
		UploadProcessWebRequest.setUploadInfo(request, info);
	}
	
	@Override
	protected void onUploadUpdate(int bytesUploaded, int total) {
//		log.debug("Uploaded: " + bytesUploaded + "/" + total); >> creates a lot of log entries
		HttpServletRequest request = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
		UploadProcessInfo info = (UploadProcessInfo)UploadProcessWebRequest.getUploadInfo(request);
		if(info == null){
			throw new IllegalStateException("could not find UploadProcessingInfo object in session which should have been set when uploaded started");
		}
		info.setBytesUploaded(bytesUploaded);
		UploadProcessWebRequest.setUploadInfo(request, info);
	}
	
	@Override
	protected void onUploadCompleted() {
		log.debug("Upload completed.");
		HttpServletRequest request = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
		UploadProcessInfo info = (UploadProcessInfo)UploadProcessWebRequest.getUploadInfo(request);
		if(info==null)
			throw new IllegalStateException("could not find UploadProcessingInfo object in session which should have been set when uploaded started");
		info.setProcessingStatus(UploadProcessInfo.PROCESSING_STARTED);
		UploadProcessWebRequest.setUploadInfo(request, info);
	}
}
